package com.baidu.push.example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

/**
 * bean util.
 *
 * @author Zhaocaipeng
 * since 2013-9-16
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class JsonObject {

    private Map<String, Object> map = new HashMap<String, Object>();

    public void setValue(String path, Object value) {
        setValue(path, value, false);
    }

    public void setValue(String path, Object value, Boolean isArray) {
        String[] pathArr = path.split("\\.");
        Object currentPathObj = map;
        for (int i = 0; i < pathArr.length - 1; i++) {
            Object tempObject = null;
            if (pathArr[i].endsWith("]")) {
                Integer index = 0;
                if (currentPathObj instanceof Map) {
                    index = Integer.valueOf(pathArr[i].substring(pathArr[i].indexOf("[") + 1,
                            pathArr[i].lastIndexOf("]")));
                    pathArr[i] = pathArr[i].substring(0, pathArr[i].indexOf("["));
                    tempObject = ((Map) currentPathObj).get(pathArr[i]);
                } else {

                }
                if (tempObject == null) {
                    tempObject = new ArrayList(index);
                    for (int j = 0; j <= index; j++) {
                        ((List) tempObject).add(new HashMap());
                    }
                    ((Map) currentPathObj).put(pathArr[i], tempObject);
                    tempObject = ((List) tempObject).get(index);
                }
            } else {

                if (currentPathObj instanceof Map) {
                    tempObject = ((Map) currentPathObj).get(pathArr[i]);
                } else {
                    //todo
                }

                if (tempObject == null) {
                    tempObject = new HashMap();
                    ((Map) currentPathObj).put(pathArr[i], tempObject);
                }

            }
            currentPathObj = tempObject;
        }

        ((Map) currentPathObj).put(pathArr[pathArr.length - 1], value);

    }

    public Map<String, Object> getData() {
        return map;
    }

    public String getJsonData() {
        return new JSONObject(this.map).toString();
    }
}
